package com.yang.service.wximpl;

import com.yang.bean.MarketStorage;
import com.yang.bean.common.BaseRespVo;
import com.yang.mapper.MarketStorageMapper;
import com.yang.service.wx.WxStorageService;
import com.yang.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author dinghongrui
 * @create 2022/09/09 14:51
 */
@Service
public class WxStorageServiceImpl implements WxStorageService {
    @Autowired
    MarketStorageMapper marketStorageMapper;


    @Override
    public BaseRespVo uploadFile(MultipartFile file) {
        MarketStorage marketStorage = new MarketStorage();
        long size = file.getSize();
        String contentType = file.getContentType();
        String name = file.getName();
        String baseName = UUID.randomUUID().toString();
        baseName = baseName + name;
        File myFile = new File(Constant.BASEPATH + baseName);
        if (!myFile.getParentFile().exists()) {
            myFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(myFile);
        } catch (IOException e) {

            return BaseRespVo.error("文件上传失败");
        }
        String url = Constant.URL + "static/" + baseName;
        marketStorage.setKey(baseName);
        marketStorage.setName(name);
        marketStorage.setType(contentType);
        marketStorage.setSize((int) size);
        marketStorage.setUrl(url);
        Date date = new Date();
        marketStorage.setAddTime(date);
        marketStorageMapper.insertSelective(marketStorage);
        marketStorage.setUpdateTime(date);
        return BaseRespVo.ok(marketStorage);
    }
}
